<?php


namespace common\service;


use common\model\ContractModel;
use common\model\OrderModel;
use common\model\UserModel;
use common\validate\Order;
use teamones\Request;

class SupplierService
{

    /**
     * 供应商列表
     * @param $param
     * @param $tenantId
     * @return mixed
     * @throws \Exception
     */
    public function select($param, $tenantId)
    {
        $param['filter'] = rollback_parser_filter($param['filter'] ?? []);
        $res = teamones_request('teamones-im', 'supplier/select', $param)['data'];
        if (!empty($res['rows'])) {

            $contractIdArray = [];
            $userIdList = [];
            foreach ($res['rows'] as $row) {
                if ((int)$row['framework_agreement_contract_id'] > 0) {
                    $contractIdArray[] = $row['framework_agreement_contract_id'];
                }
                if ($row['user_id'] > 0) {
                    $userIdList[$row['user_id']] = $row['user_id'];
                }
            }
            $contractData = [];
            if (count($contractIdArray) > 0) {
                $contractData = model(ContractModel::class)->where(['id' => ['IN', implode(',', $contractIdArray)]])->select();
                $contractData = array_map(function ($c) {
                    CommonService::getFormatAttrData(model(ContractModel::class), $c);
                    return $c;
                }, $contractData);
                $contractData = array_column($contractData, null, 'id');
            }
            $userData = [];
            if (count($userIdList)) {
                $userData = model(UserModel::class)->where(['union_id' => ['IN', array_values($userIdList)]])->field('id,name,phone,email,avatar,union_id')->select();
                $userData = array_column($userData, null, 'union_id');
            }

            // 查出当前租户属于哪个集团
            $tenantGroupMemberParam = [
                'param' => [
                    'filter' => ['tenant_id' => $tenantId]
                ]
            ];
            $tenantGroupMemberData = teamones_request('teamones-im', 'tenant_group_member/list', $tenantGroupMemberParam);

            $nowTenantMemberGroupIds = [];
            if (!empty($tenantGroupMemberData['data'])) {
                $nowTenantMemberGroupIds = array_column($tenantGroupMemberData['data']['rows'], 'tenant_group_id');
            }

            // 查询供应商所属集团
            $fromTenantIds = array_column($res['rows'], 'from_tenant_id');
            $fromTenantIdData = teamones_request('teamones-im', 'tenant_group_member/list', [
                'param' => [
                    'filter' => ['tenant_id' => ['-in', join(',', $fromTenantIds)]],
                    'fields' => 'tenant_id,tenant_group_id'
                ]
            ]);

            $tenantGroupMemberMap = [];
            if (!empty($fromTenantIdData['data']['rows'])) {

                $tenantGroupMemberMap = array_group_by($fromTenantIdData['data']['rows'], 'tenant_id');
                $tenantGroupMemberMap = array_map(function ($tmp) {
                    return array_column($tmp, 'tenant_group_id');
                }, $tenantGroupMemberMap);
            }

            $fromTenantIds = array_column($res['rows'], 'from_tenant_id');
            $orderData = model(OrderModel::class)
                ->where(['to_tenant_id' => ['IN', $fromTenantIds], 'from_tenant_id' => $tenantId, 'status' => 'done'])
                ->field('to_tenant_id,count(id) as num')
                ->group('to_tenant_id')
                ->select();
            $orderMap = array_column($orderData, null, 'to_tenant_id');

            $res['rows'] = array_map(function ($row) use (&$contractData, &$userData, $orderMap, $nowTenantMemberGroupIds, $tenantGroupMemberMap) {
                $row['framework_agreement_contract'] = $contractData[$row['framework_agreement_contract_id']] ?? null;
                $row['saas_user'] = $userData[$row['user_id']] ?? null;
                $row['find_order_num'] = $orderMap[$row['from_tenant_id']]['num'] ?? 0; // 完成订单数量
                $tenantGroupMemberIds = $tenantGroupMemberMap[$row['from_tenant_id']] ?? [];
                $row['tenant_group_in'] = boolval(array_intersect($nowTenantMemberGroupIds, $tenantGroupMemberIds)); // 是否在集团内
                $row['now_tenant_member_group_ids'] = $nowTenantMemberGroupIds;
                $row['tenant_group_member_list'] = $tenantGroupMemberMap[$row['from_tenant_id']] ?? [];
                return $row;
            }, $res['rows']);
        }

        return $res;
    }

    /**
     * 查询供应商详情
     * @param $param
     * @return mixed
     * @throws \Exception
     */
    public function findSupplier($param)
    {
        $res = teamones_request('teamones-im', 'supplier/find_supplier', $param)['data'];
        if (empty($res)) {
            return $res;
        }
        $res['framework_agreement_contract'] = null;
        if ((int)$res['framework_agreement_contract_id'] > 0) {
            $res['framework_agreement_contract'] = model(ContractModel::class)->where(['id' => $res['framework_agreement_contract_id']])->findData();
        }
        return $res;
    }

    /**
     * 等待签署的供应商
     * @return array|mixed|string
     * @throws \Exception
     */
    public function waitForSignSelect($param)
    {
        $param['filter'] = rollback_parser_filter($param['filter'] ?? []);
        $res = teamones_request('teamones-im', 'supplier/get_supplier_customer_list', $param);
        $res = $res['data'] ?? [];

        if (!empty($res)) {
            $contractIdArray = [];
            $userIdList = [];
            foreach ($res as $row) {
                if ((int)$row['framework_agreement_contract_id'] > 0) {
                    $contractIdArray[] = $row['framework_agreement_contract_id'];
                }
                if ($row['user_id'] > 0) {
                    $userIdList[$row['user_id']] = $row['user_id'];
                }
            }
            $contractData = [];
            if (count($contractIdArray) > 0) {
                $contractData = model(ContractModel::class)->where(['id' => ['IN', implode(',', $contractIdArray)]])->selectData();
                $contractData = array_column($contractData['rows'], null, 'id');
            }
            $userData = [];
            if (count($userIdList)) {
                $userData = model(UserModel::class)->where(['union_id' => ['IN', array_values($userIdList)]])->field('id,name,phone,email,avatar,union_id')->select();
                $userData = array_column($userData, null, 'union_id');
            }
            $res = array_map(function ($row) use (&$contractData, &$userData) {
                $row['framework_agreement_contract'] = $contractData[$row['framework_agreement_contract_id']] ?? null;
                $row['saas_user'] = $userData[$row['user_id']] ?? null;
                return $row;
            }, $res);
        }

        return $res;
    }

}
